﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.System.User;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.System.Area;
using Modules.System.Menu;
using Modules.System.Security;
using Modules.System.User;
using PmSoft;
using PmSoft.Utilities;

namespace ManagementApi.Controllers.SystemManage
{
    /// <summary>
    /// 用户接口
    /// </summary>
    [Route("/api/v1/users")]
    [ApiController]
    //[Authorize(Roles = "SysUser")]
    public class UserController : ControllerBase
    {
        private readonly SystemUserApplicationContext applicationContext;
        private readonly UserService userSevice;
        private readonly AreaService areaService;
        private readonly IMapper mapper;
        private readonly SecurityService securityService;
        //private readonly UserServiceTest userServiceTest;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UserController(SystemUserApplicationContext applicationContext,
            UserService userSevice,
            MenuService menuService,
            AreaService areaService,
            IMapper mapper,
            SecurityService securityService
            //, UserServiceTest userServiceTest
            )
        {
            this.applicationContext = applicationContext;
            this.userSevice = userSevice;
            this.mapper = mapper;
            this.areaService = areaService;
            this.securityService = securityService;
            //this.userServiceTest = userServiceTest;
        }

        /// <summary>
        /// 获取用户列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<UserDto>> GetUsers([FromQuery] UserQuery query, int pageNum = 1, int pageSize = 20)
        {
            var users = userSevice.GetUsers(query, pageNum, pageSize);
            var dtos = users.AsPageDto(source => { return source.AsUserDto(); });
            return ApiResult<PageDto<UserDto>>.Success(dtos);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("create")]
        [PermissionCheck("sys:user:add")]
        public ApiResult Add([FromBody] UserCreateForm form)
        {
            SysUser user = new SysUser();
            mapper.Map(form, user);
            var areaCodes = areaService.GetAreaTuple(form.AreaId ?? 0);
            user.ProvinceCode = areaCodes.ProvinceCode;
            user.CityCode = areaCodes.CityCode;
            user.AreaCode = areaCodes.AreaCode;
            userSevice.CreateUser(user, form.Password, form.RoleIds);
            return ApiResult.Success("创建成功");
        }

        /// <summary>
        /// 用户表单数据
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<UserEditForm> GetRole(int id)
        {
            var user = userSevice.GetUser(id);
            if (user == null)
                return ApiResult<UserEditForm>.Failure("用户数据不存在");
            UserEditForm userEditForm = new UserEditForm();
            mapper.Map(user, userEditForm);
            userEditForm.RoleIds = user.GetRoleIds();
            return ApiResult<UserEditForm>.Success(userEditForm);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userEditForm"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [PermissionCheck("sys:user:edit")]
        public ApiResult Update(int id, [FromBody] UserEditForm userEditForm)
        {
            var user = userSevice.GetUser(id);
            if (user == null) return ApiResult.Failure("用户不存在");
            mapper.Map(userEditForm, user);
            var areaCodes = areaService.GetAreaTuple(userEditForm.AreaId ?? 0);
            user.ProvinceCode = areaCodes.ProvinceCode;
            user.CityCode = areaCodes.CityCode;
            user.AreaCode = areaCodes.AreaCode;
            userSevice.UpdateUser(user, userEditForm.RoleIds);
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [PermissionCheck("sys:user:delete")]
        public ApiResult Delete(string ids)
        {
            userSevice.DeleteUserIds(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPatch("{id}/password")]
        [PermissionCheck("sys:user:reset_pwd")]
        public ApiResult UpdatePassword(int id, string password)
        {
            userSevice.UpdatePassword(id, password);
            return ApiResult.Success("密码重置成功");
        }

        /// <summary>
        /// 事务测试
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("TranTest")]
        [ServiceFilter(typeof(TransactionFilter))]
        public ApiResult<SysUserSugar> TranTest(int id)
        {
            SysUserSugar data = userSevice.TranTest(id);
            return ApiResult<SysUserSugar>.Success(data);
        }
    }
}